package org.xfy.ymcc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.xfy.ymcc.domain.Login;
import org.xfy.ymcc.domain.Permission;
import org.xfy.ymcc.mapper.LoginMapper;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private LoginMapper loginMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //security的登陆验证
        Login login = loginMapper.selectOne(new LambdaQueryWrapper<Login>().eq(Login::getUsername, username));
        if (login!=null){
            //证明用户存在，验证密码
            //去查询该用户当前拥有的权限
            List<Permission>permissions=loginMapper.getAuth(login.getId());
            List<SimpleGrantedAuthority> collect = permissions.stream()
                    .map(permission -> new SimpleGrantedAuthority(permission.getSn()))
                    .collect(Collectors.toList());
            User user = new User(username,login.getPassword(),collect);
            return user;
        }
        return null;
    }
}
